<template>
  <MainLayout current-page="chat">
    <!-- 三栏布局：当前对话目录区 + 聊天内容区 -->
    <div class="flex">
      <!-- 当前对话目录区 - 添加收缩功能 -->
      <div 
        :class="[
          'bg-white flex flex-col sticky top-0 h-screen z-0 transition-all duration-300',
          isDirectoryCollapsed ? 'w-12' : 'w-65'
        ]"
      >
        <div class="p-4 flex flex-col h-full">
          <!-- 目录标题和收缩按钮 -->
          <div class="flex items-center justify-between mb-4 flex-shrink-0">
            <div 
              v-if="!isDirectoryCollapsed" 
              class="font-medium text-base text-gray-800"
            >
              当前对话目录
            </div>
            <button
              @click="toggleDirectory"
              class="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-gray-200 transition-colors flex-shrink-0"
              :title="isDirectoryCollapsed ? '展开目录' : '收缩目录'"
            >
              <i :class="[
                'fas transition-transform duration-300',
                isDirectoryCollapsed ? 'fa-chevron-right' : 'fa-chevron-left'
              ]"></i>
            </button>
          </div>
          
          <!-- 目录内容 - 收缩时隐藏 -->
          <div v-if="!isDirectoryCollapsed" class="space-y-4 overflow-y-auto flex-1 min-h-0">
            <div 
              v-for="(item, index) in chatHistory" 
              :key="index"
              @click="scrollToMessage(index)"
              :class="[
                'bg-gray-50 rounded-lg p-3 cursor-pointer hover:bg-gray-100 transition-all',
                activeMessageIndex === index ? 'bg-blue-50 border border-blue-200' : ''
              ]"
            >
              <!-- 问题显示 -->
              <div class="text-sm font-medium mb-3 text-gray-800">
                {{ truncateText(item.question, 15) }}
              </div>
              
              <!-- 模型回答列表 -->
              <div class="space-y-2">
                <div 
                  v-for="model in selectedModelsForChat" 
                  :key="model.modelKey"
                  class="bg-white rounded-lg p-2"
                >
                  <div class="flex items-center mb-1">
                    <!-- 模型图标 -->
                    <div :class="['w-4 h-4 rounded flex items-center justify-center mr-2', model.colorClass]">
                      <i :class="[model.iconClass, 'text-xs']"></i>
                    </div>
                    <!-- 模型名称 -->
                    <span class="text-xs font-medium text-gray-700">{{ model.name }}的回答</span>
                  </div>
                  <!-- 回答内容预览 -->
                  <div class="text-xs text-gray-500 line-clamp-2">
                    <template v-if="item.responses?.[model.modelKey]?.content">
                      {{ truncateText(item.responses[model.modelKey].content, 13) }}
                    </template>
                    <template v-else-if="item.responses?.[model.modelKey]?.status === 'streaming'">
                      <span class="text-blue-500">正在生成回答...</span>
                    </template>
                    <template v-else>
                      <span class="text-gray-400">等待响应...</span>
                    </template>
                  </div>
                </div>
              </div>
              
              <!-- 时间戳 -->
              <div class="text-xs text-gray-400 mt-2">
                <span v-if="item.roundNumber">第{{ item.roundNumber }}轮 </span>
                <span>{{ item.timestamp ? item.timestamp.toLocaleString().substring(0, 16) : '未知时间' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 聊天内容区域 -->
      <div class="flex-1">
        <div class="max-w-4xl mx-auto p-6 pb-40">
          <!-- 聊天内容滚动区域 -->
          <div ref="chatContentRef" class="flex-1 overflow-y-auto pr-2 mb-20">
            <!-- 历史对话区域 -->
            <div 
              v-for="(item, index) in chatHistory" 
              :key="index" 
              :id="`message-${index}`"
              class="mb-4 scroll-mt-8"
            >
              <!-- 用户问题 -->
              <div class="flex justify-end mb-6">
                <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
                  <div class="text-lg font-medium text-gray-800">{{ item.question }}</div>
                </div>
              </div>

              <!-- AI模型响应 -->
              <div 
                v-for="model in selectedModelsForChat" 
                :key="`history-${index}-${model.id}`"
                class="mb-8"
              >
                <div class="bg-white rounded-xl pl-0 pt-0 pb-5 border-gray-100">
                  <div class="flex items-center mb-4">
                    <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                      <i :class="[model.iconClass, 'text-sm']"></i>
                    </div>
                    <span class="font-medium text-gray-800">{{ model.name }}</span>
                  </div>
                  <div class="text-gray-700">
                    <div class="prose prose-sm max-w-none">
                      <!-- 思考过程 -->
                      <div v-if="item.responses?.[model.modelKey]?.thinkingContent" class="mb-4">
                        <div class="bg-gray-50 rounded-lg border border-gray-200">
                          <div 
                            @click="toggleThinking(`history-${index}-${model.modelKey}`)"
                            class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                          >
                            <div class="flex items-center">
                              <span class="text-sm font-medium text-gray-800">思考过程</span>
                              <span class="text-xs text-gray-600 ml-2">
                                ({{ item.responses?.[model.modelKey]?.thinkingContent?.length || 0 }} 字符)
                              </span>
                            </div>
                          </div>
                          <div 
                            v-show="isThinkingExpanded(`history-${index}-${model.modelKey}`)"
                            class="px-4 pb-4 border-t border-gray-200"
                          >
                            <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">
                              {{ item.responses?.[model.modelKey]?.thinkingContent }}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 回答内容 -->
                      <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                        {{ item.responses?.[model.modelKey]?.content || '暂无回复内容' }}
                      </div>
                      <div class="text-xs text-gray-400 mt-3">
                        回复时间：{{ formatTimestamp(item.responses?.[model.modelKey]?.timestamp) }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 当前对话区域 -->
            <div 
              v-if="isProcessing || Object.keys(currentStreamingResponses).length > 0" 
              id="current-message"
              class="mb-8 scroll-mt-8"
            >
              <!-- 当前用户问题 -->
              <div class="flex justify-end mb-6">
                <div class="bg-gray-100 rounded-xl p-4 max-w-lg">
                  <div class="text-lg font-medium text-gray-800">{{ currentQuestion }}</div>
                </div>
              </div>

              <!-- 当前AI模型响应 -->
              <div 
                v-for="model in selectedModelsForChat" 
                :key="`current-${model.id}`"
                class="mb-8"
              >
                <div class="bg-white rounded-xl pl-0 pt-0 pb-5 border-gray-100">
                  <div class="flex items-center mb-4">
                    <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                      <i :class="[model.iconClass, 'text-sm']"></i>
                    </div>
                    <span class="font-medium text-gray-800">{{ model.name }}</span>
                  </div>
                  <div>
                    <div v-if="isProcessing && !getModelResponse(model.modelKey)" class="flex items-center text-gray-500">
                      <i class="fas fa-spinner fa-spin mr-2"></i>
                      <span>AI正在思考中...</span>
                    </div>
                    <div v-else class="text-gray-700">
                      <!-- 可折叠的思考过程显示 -->
                      <div v-if="getModelResponse(model.modelKey)?.thinkingContent" class="mb-4">
                        <div class="bg-gray-50 rounded-lg border border-gray-200">
                          <div 
                            @click="toggleThinking(model.modelKey)"
                            class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                          >
                            <div class="flex items-center">
                              <span class="text-sm font-medium text-gray-800">思考过程</span>
                              <span class="text-xs text-gray-600 ml-2">
                                ({{ getModelResponse(model.modelKey)?.thinkingContent?.length || 0 }} 字符, {{ getThinkingDuration(model.modelKey) }} 秒)
                              </span>
                            </div>
                          </div>
                          
                          <div 
                            v-show="isThinkingExpanded(model.modelKey)"
                            class="px-4 pb-4 border-t border-gray-200"
                          >
                            <div class="text-sm text-gray-800 whitespace-pre-wrap pt-3">
                              {{ getModelResponse(model.modelKey)?.thinkingContent }}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 流式响应内容 -->
                      <div v-if="getModelResponse(model.modelKey)?.status === 'streaming'" class="prose prose-sm max-w-none">
                        <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                          {{ getModelResponse(model.modelKey)?.content || '正在生成回答...' }}
                        </div>
                        <div class="text-xs text-gray-400 mt-3">
                          正在流式输出中...
                        </div>
                      </div>
                      <!-- 成功响应 -->
                      <div v-else-if="getModelResponse(model.modelKey)?.status === 'success'" class="prose prose-sm max-w-none">
                        <div class="whitespace-pre-wrap bg-gray-50 rounded-lg p-4 border border-gray-200">
                          {{ getModelResponse(model.modelKey)?.content || '暂无回复内容' }}
                        </div>
                        <div class="text-xs text-gray-400 mt-3">
                          回复时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                        </div>
                      </div>
                      <!-- 错误响应 -->
                      <div v-else-if="getModelResponse(model.modelKey)?.status === 'error'" class="text-red-600">
                        <div class="flex items-start">
                          <i class="fas fa-exclamation-triangle mr-2 mt-1 flex-shrink-0"></i>
                          <div>
                            <div class="font-medium mb-1">请求失败</div>
                            <div class="text-sm text-red-500">{{ getModelResponse(model.modelKey)?.error || '未知错误' }}</div>
                            <div class="text-xs text-gray-400 mt-2">
                              错误时间：{{ formatTimestamp(getModelResponse(model.modelKey)?.timestamp) }}
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 无响应数据 -->
                      <div v-else class="text-gray-500 italic">
                        <i class="fas fa-clock mr-2"></i>
                        等待响应中...
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 固定底部输入框 - 根据目录收缩状态调整位置 -->
    <div 
      :class="[
        'fixed bottom-0 right-0 bg-transparent z-50 transition-all duration-300',
        isDirectoryCollapsed ? 'left-[130px]' : 'left-[340px]'
      ]"
    >
      <div class="max-w-4xl mx-auto pl-6 pr-6 pt-6 pb-0">
        <div class="bg-white rounded-1xl border-gray-200 pt-0 pb-6">
          <!-- 顶部返回按钮区域 -->
          <div class="flex justify-end mb-0 mr-3 p-3">
            <button @click="router.push('/')" class="text-primary hover:text-primary/80 font-medium text-sm flex items-center">
              <i class="fas fa-home mr-2"></i>
              返回首页
            </button>
          </div>
          <div class="bg-white rounded-2xl border border-gray-200 p-6">
            <div class="relative">
              <textarea 
                v-model="chatInput"
                class="w-full border-none bg-gray-50/70 rounded-2xl pl-6 pr-32 py-5 resize-none focus:ring-2 focus:ring-primary focus:outline-none text-base" 
                rows="3" 
                placeholder="继续对话..."
              ></textarea>
              <div class="absolute right-4 bottom-4 flex items-center space-x-2">
                <button @click="handleMicrophone" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-microphone"></i>
                </button>
                <button @click="handleUpload" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                  <i class="fas fa-paperclip"></i>
                </button>
                <button @click="sendMessage" class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90">
                  <i class="fas fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import MainLayout from '@/components/layout/MainLayout.vue'
import { 
  formatTimestamp, 
  getModelDisplayConfig, 
  getModelDisplayName
} from '@/utils/chatUtils'
import type { 
  AiModel, 
  ChatHistoryItem, 
  StreamResponse
} from '@/types/chat'

const route = useRoute()
const router = useRouter()

// 使用 ref 定义 conversationId，使其可以响应式更新
const conversationId = ref(route.params.conversationId as string)

// 其他状态变量
const chatHistory = ref<ChatHistoryItem[]>([])
const currentQuestion = ref('')
const isProcessing = ref(false)
const chatInput = ref('')
const aiModels = ref<AiModel[]>([])
const selectedModelsForChat = ref<AiModel[]>([])
const currentStreamingResponses = ref<{ [key: string]: StreamResponse }>({})
const thinkingExpanded = ref<{ [key: string]: boolean }>({})

// 新增状态变量
const chatContentRef = ref<HTMLElement>()
const activeMessageIndex = ref<number>(-1)
const isDirectoryCollapsed = ref<boolean>(false) // 新增：目录收缩状态

// 切换目录收缩状态
const toggleDirectory = () => {
  isDirectoryCollapsed.value = !isDirectoryCollapsed.value
}

// 监听路由参数变化
watch(() => route.params.conversationId, (newConversationId, oldConversationId) => {
  if (newConversationId && newConversationId !== oldConversationId) {
    // 路由参数变化时重新加载对话详情
    conversationId.value = newConversationId as string
    loadConversationDetails()
  }
})

// 获取AI模型数据
const fetchAiModels = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/ai-models/active`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        aiModels.value = result.data.map((model: any) => {
          return {
            id: model.id,
            name: model.displayName,
            modelKey: model.name,
            icon: model.icon,
            iconClass: model.iconClass || 'fas fa-robot',
            colorClass: model.colorClass || 'bg-gray-100 text-gray-600',
            selected: false,
            free: model.isFree,
            modelDescription: model.modelDescription,
            rankPosition: model.rankPosition,
            flowersCount: model.flowersCount,
            eggsCount: model.eggsCount,
            popularityScore: model.popularityScore,
            discussionsCount: model.discussionsCount,
            responseSpeedScore: model.responseSpeedScore,
            accuracyScore: model.accuracyScore,
            copywritingScore: model.copywritingScore,
            drawingScore: model.drawingScore,
            programmingScore: model.programmingScore
          }
        })
      }
    }
  } catch (error) {
    console.error('获取AI模型错误:', error)
  }
}

// 加载对话详情
const loadConversationDetails = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/conversation/${conversationId.value}`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        const data = result.data
        
        // 后端已经返回正确格式，直接使用
        chatHistory.value = (data.messages || []).map((item: any) => ({
          question: item.question || '',
          responses: item.responses || {},
          timestamp: item.timestamp ? new Date(item.timestamp) : new Date(),
          roundNumber: item.roundNumber, // 添加轮次编号
          isFirstRound: item.isFirstRound // 添加是否首轮标识
        }))
        
        // 设置选中的模型
        if (data.models) {
          selectedModelsForChat.value = data.models.map((modelInfo: any) => {
            const model = aiModels.value.find(m => m.id === modelInfo.id)
            return model || {
              id: modelInfo.id,
              name: modelInfo.name,
              modelKey: modelInfo.modelKey,
              iconClass: 'fas fa-robot',
              colorClass: 'bg-gray-100 text-gray-600',
              selected: false,
              free: false
            }
          })
        }
      }
    }
  } catch (error) {
    console.error('加载对话详情失败:', error)
    ElMessage.error('加载对话详情失败')
  }
}

// 转换后端消息格式为前端期望的聊天历史格式
const transformMessagesToChatHistory = (messages: any[], models: any[]) => {
  // 按轮次分组消息
  const messagesByRound: { [roundNumber: string]: any[] } = {}
  
  messages.forEach(msg => {
    const roundNumber = msg.round_number || '1'
    if (!messagesByRound[roundNumber]) {
      messagesByRound[roundNumber] = []
    }
    messagesByRound[roundNumber].push(msg)
  })
  
  // 构建聊天历史
  const chatHistory: ChatHistoryItem[] = []
  
  Object.entries(messagesByRound).forEach(([roundNumber, roundMessages]) => {
    // 找到用户问题
    const userMessage = roundMessages.find(msg => msg.role === 'USER')
    if (!userMessage) return
    
    // 按模型分组助手回复，保持模型顺序
    const responses: { [modelKey: string]: any } = {}
    
    // 按照 models 数组的顺序来处理响应
    models.forEach(modelInfo => {
      const modelKey = modelInfo.modelKey || modelInfo.name
      const assistantMessage = roundMessages.find(msg => 
        msg.role === 'ASSISTANT' && msg.model_name === modelInfo.name
      )
      
      if (assistantMessage) {
        responses[modelKey] = {
          content: assistantMessage.content || '',
          thinkingContent: assistantMessage.thinking_content || '',
          timestamp: assistantMessage.created_at ? new Date(assistantMessage.created_at) : new Date(),
          status: 'success'
        }
      }
    })
    
    chatHistory.push({
      question: userMessage.content || '',
      responses: responses,
      timestamp: userMessage.created_at ? new Date(userMessage.created_at) : new Date(),
      roundNumber: parseInt(roundNumber, 10), // 添加轮次编号
      isFirstRound: parseInt(roundNumber, 10) === 1 // 添加是否首轮标识
    })
  })
  
  // 按时间排序
  return chatHistory.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())
}

// 更新流式响应的辅助函数
const updateStreamingResponse = (modelKey: string, updates: Partial<StreamResponse>) => {
  if (currentStreamingResponses.value[modelKey]) {
    currentStreamingResponses.value[modelKey] = {
      ...currentStreamingResponses.value[modelKey],
      ...updates
    }
  } else {
    currentStreamingResponses.value[modelKey] = {
      modelKey,
      modelName: '',
      content: '',
      thinkingContent: '',
      status: 'streaming',
      timestamp: new Date(),
      ...updates
    }
  }
}

// 处理流式响应
const handleStreamResponse = async (model: AiModel, question: string) => {
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
  
  const payload = {
    question: question,
    modelId: model.id,
    conversationId: conversationId.value, // 使用 ref 的值
    history: chatHistory.value,
    contextSize: 5
  }
  
  try {
    const response = await fetch(`${baseURL}/chat/ask-stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 初始化流式响应状态（保持原有逻辑）
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'streaming',
      timestamp: new Date()
    })
    
    // 新增：累积数据的变量
    let accumulatedContent = ''
    let accumulatedThinking = ''
    
    // 处理 Server-Sent Events 流（保持原有显示逻辑）
    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }
    
    const decoder = new TextDecoder()
    let buffer = ''
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        updateStreamingResponse(model.modelKey, {
          status: 'success',
          timestamp: new Date()
        })
        // 流式完成，保存完整内容到后端
        await saveCompleteResponse(model.modelKey, accumulatedContent, accumulatedThinking)
        break
      }
      
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        if (line.trim() === '') continue
        
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          
          try {
            const streamingOutput = JSON.parse(data)
            
            if (streamingOutput.type === 'thinking' && streamingOutput.data) {
              // 保持原有显示逻辑
              const currentThinking = currentStreamingResponses.value[model.modelKey]?.thinkingContent || ''
              updateStreamingResponse(model.modelKey, {
                thinkingContent: currentThinking + streamingOutput.data
              })
              
              // 新增：累积思考内容
              accumulatedThinking += streamingOutput.data
              
            } else if (streamingOutput.type === 'content' && streamingOutput.data) {
              // 保持原有显示逻辑
              const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
              updateStreamingResponse(model.modelKey, {
                content: currentContent + streamingOutput.data
              })
              
              // 新增：累积回复内容
              accumulatedContent += streamingOutput.data
              
            } else if (streamingOutput.type === 'done') {
              // 流式完成，保存完整内容到后端
              await saveCompleteResponse(model.modelKey, accumulatedContent, accumulatedThinking)
              
              updateStreamingResponse(model.modelKey, {
                status: 'success',
                timestamp: new Date()
              })
              return
            } else if (streamingOutput.type === 'error') {
              updateStreamingResponse(model.modelKey, {
                status: 'error',
                error: streamingOutput.data || '未知错误',
                timestamp: new Date()
              })
              return
            }
          } catch (parseError) {
            console.warn('解析流式输出失败:', parseError)
            // 保持原有显示逻辑
            const currentContent = currentStreamingResponses.value[model.modelKey]?.content || ''
            updateStreamingResponse(model.modelKey, {
              content: currentContent + data
            })
            
            // 新增：累积内容
            accumulatedContent += data
          }
        }
      }
    }
    
  } catch (error) {
    console.error(`模型 ${model.name} 流式请求失败:`, error)
    
    updateStreamingResponse(model.modelKey, {
      modelName: model.name,
      content: '',
      thinkingContent: '',
      status: 'error',
      error: error instanceof Error ? error.message : '网络错误',
      timestamp: new Date()
    })
  }
}

// 新增：保存完整响应的函数
const saveCompleteResponse = async (modelKey: string, content: string, thinking: string) => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/chat/save-response`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        conversationId: conversationId.value, // 使用 ref 的值
        modelKey: modelKey,
        content: content,
        thinking: thinking
      })
    })
    
    if (response.ok) {
      console.log('完整响应保存成功:', modelKey)
    } else {
      console.error('保存完整响应失败:', modelKey)
    }
  } catch (error) {
    console.error('保存完整响应错误:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  // 如果没有当前问题，从 sessionStorage 获取
  if (!currentQuestion.value) {
    const savedQuestion = sessionStorage.getItem('currentQuestion')
    if (savedQuestion) {
      currentQuestion.value = savedQuestion
      sessionStorage.removeItem('currentQuestion')
    }
  }
  
  // 如果当前问题为空，使用输入框的内容
  if (!currentQuestion.value.trim() && chatInput.value.trim()) {
    currentQuestion.value = chatInput.value.trim()
  }
  
  if (!currentQuestion.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  isProcessing.value = true
  currentStreamingResponses.value = {}
  
  try {
    // 并发启动多个流式请求
    const streamPromises = selectedModelsForChat.value.map(model => 
      handleStreamResponse(model, currentQuestion.value)
    )
    
    // 等待所有流式请求完成
    await Promise.allSettled(streamPromises)
    
    // 按照 selectedModelsForChat 的顺序构建 responses 对象
    const orderedResponses: { [key: string]: StreamResponse } = {}
    selectedModelsForChat.value.forEach(model => {
      if (currentStreamingResponses.value[model.modelKey]) {
        orderedResponses[model.modelKey] = currentStreamingResponses.value[model.modelKey]
      }
    })
    
    // 将流式响应保存到聊天历史
    chatHistory.value.push({
      question: currentQuestion.value,
      responses: orderedResponses, // 使用有序的响应对象
      timestamp: new Date()
    })
    
    // 清空当前流式响应和问题
    currentStreamingResponses.value = {}
    currentQuestion.value = ''
    chatInput.value = ''
    
    ElMessage.success('消息发送成功')
    
  } catch (error) {
    console.error('发送消息错误:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 获取模型响应数据
const getModelResponse = (modelKey: string) => {
  return currentStreamingResponses.value[modelKey]
}

// 计算思考过程时长
const getThinkingDuration = (modelKey: string) => {
  const response = currentStreamingResponses.value[modelKey]
  if (!response || !response.timestamp) return 0
  
  const startTime = new Date(response.timestamp).getTime()
  const endTime = new Date().getTime()
  const duration = Math.floor((endTime - startTime) / 1000)
  
  return Math.max(0, duration)
}

// 切换思考过程展开状态
const toggleThinking = (modelKey: string) => {
  thinkingExpanded.value[modelKey] = !thinkingExpanded.value[modelKey]
}

// 检查思考过程是否展开
const isThinkingExpanded = (modelKey: string) => {
  return thinkingExpanded.value[modelKey] || false
}

// 文本截断函数
const truncateText = (text: string | undefined | null, maxLength: number) => {
  const safeText = text || '';
  if (safeText.length <= maxLength) {
    return safeText;
  }
  return safeText.substring(0, maxLength) + '...';
};

// 格式化时间戳
const formatTime = (timestamp: Date | undefined | null) => {
  if (!timestamp) {
    return '未知时间';
  }
  return timestamp.toLocaleString().substring(0, 16);
};

// 按钮事件处理
const handleMicrophone = () => {
  ElMessage.info('语音功能开发中...')
}

const handleUpload = () => {
  ElMessage.info('上传功能开发中...')
}

// 滚动到指定消息
const scrollToMessage = (index: number) => {
  activeMessageIndex.value = index
  
  // 使用 nextTick 确保 DOM 更新完成
  nextTick(() => {
    const targetElement = document.getElementById(`message-${index}`)
    if (targetElement && chatContentRef.value) {
      // 滚动到目标元素，使用平滑滚动
      targetElement.scrollIntoView({ 
        behavior: 'smooth', 
        block: 'start' 
      })
      
      // 移除高亮效果相关代码
      // targetElement.classList.add('highlight-message')
      // setTimeout(() => {
      //   targetElement.classList.remove('highlight-message')
      // }, 2000)
    }
  })
}

// 监听滚动事件，更新当前激活的消息索引
const handleScroll = () => {
  if (!chatContentRef.value) return
  
  const scrollTop = chatContentRef.value.scrollTop
  const messages = chatHistory.value
  
  for (let i = messages.length - 1; i >= 0; i--) {
    const element = document.getElementById(`message-${i}`)
    if (element) {
      const elementTop = element.offsetTop
      if (scrollTop >= elementTop - 100) { // 100px 的偏移量
        activeMessageIndex.value = i
        break
      }
    }
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await fetchAiModels()
  
  // 从 sessionStorage 读取选中的模型和问题
  const savedModels = sessionStorage.getItem('selectedModels')
  const savedQuestion = sessionStorage.getItem('currentQuestion')
  
  if (savedModels && savedQuestion) {
    // 设置选中的模型
    selectedModelsForChat.value = JSON.parse(savedModels)
    currentQuestion.value = savedQuestion
    
    // 清空 sessionStorage
    sessionStorage.removeItem('selectedModels')
    sessionStorage.removeItem('currentQuestion')
    
    // 自动发送消息
    await sendMessage()
  } else {
    // 如果没有保存的数据，则加载对话详情
    await loadConversationDetails()
  }
  
  // 添加滚动监听
  if (chatContentRef.value) {
    chatContentRef.value.addEventListener('scroll', handleScroll)
  }
})

// 组件卸载时移除滚动监听
onUnmounted(() => {
  if (chatContentRef.value) {
    chatContentRef.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 移除高亮消息样式 */
.highlight-message {
  /* 移除阴影和背景色动画 */
}

/* 确保滚动时有适当的偏移 */
.scroll-mt-8 {
  scroll-margin-top: 2rem;
}

/* 对话目录容器固定宽度样式 */
.w-65 {
  width: 16.25rem !important;
  min-width: 16.25rem !important;
  max-width: 16.25rem !important;
  flex-shrink: 0 !important;
}

.w-12 {
  width: 3rem !important;
  min-width: 3rem !important;
  max-width: 3rem !important;
  flex-shrink: 0 !important;
}

/* 过渡动画 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.duration-300 {
  transition-duration: 300ms;
}

/* 对话目录项固定宽度样式 */
.conversation-item {
  width: 100%;
  min-height: 120px;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.question-text {
  word-break: break-word;
  overflow-wrap: break-word;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.model-response-item {
  width: 100%;
  min-height: 60px;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.model-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: calc(100% - 1.5rem);
}

.response-preview {
  width: 100%;
  min-height: 32px;
  word-break: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
  box-sizing: border-box;
}

.timestamp {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  box-sizing: border-box;
}

/* 确保所有文本内容不会影响布局 */
.conversation-item * {
  max-width: 100%;
  box-sizing: border-box;
}
</style>